import { BadRequestException, Inject, Injectable } from '@nestjs/common'
import * as captcha from 'svg-captcha'
import * as md5 from 'md5'
import { CACHE_MANAGER } from '@nestjs/cache-manager'
import { Cache } from 'cache-manager'

@Injectable()
export class SvgCaptchaService {
   constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
   async create() {
      const svg = captcha.createMathExpr({ mathMax: 10, mathMin: 1, color: true })
      const key = md5('song!@$%xiao***' + Date.now())
      await this.cacheManager.set(key, svg.text, 60000)
      return { key, svg: svg.data }
   }

   async check(key: string, value: number) {
      const captcha_text = await this.cacheManager.get(key)
      if (captcha_text != value) throw new BadRequestException('验证码错误')
   }
}
